//
//  CS_Pop_MultitpleSelectView.m
//  Pods
//
//  Created by 网新中研 on 17/3/31.
//
//

#import "CS_Pop_MultitpleSelectView.h"

#define CELL_STYLE_MAIN_SELECTABLE_CELL @"MainSelectCell"

#define SELECT_VIEW_WIDTH 275.0
#define SELECT_CELL_HEIGHT 46.0
#define SELECT_CELL_MARGIN 30.0
#define CONTENT_LABEL_HEIGHT 40.0
#define BUTOTN_WIDTH 100.0
#define BUTTON_HEIGHT 30.0

@implementation MainSelectCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self layoutView];
    }
    return self;
}

-(void)layoutView{
    
    CGFloat imageHeight = 13.0;
    CGFloat imageWidth = imageHeight / 9.0 * 13.0;
    CGFloat labelWidth = kWindowW - 20.0 - imageWidth - 20.0;
    CGFloat labelHeight = SELECT_CELL_HEIGHT - 20.0;
    self.typeNameLabel.frame = CGRectMake(20, 10, labelWidth, labelHeight);
    [self addSubview:self.typeNameLabel];
    
    self.checkImageView.frame = CGRectMake(kWindowW - 10 - imageWidth, (SELECT_CELL_HEIGHT - imageHeight)/2.0, imageWidth, imageHeight);
    
    [self addSubview:self.checkImageView];
    
}

#define KVO_KEY_IS_SELECTED @"isSelected"

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:KVO_KEY_IS_SELECTED]) {//安装功能项修改
        {
            [self changeSelectImage:self.model.isSelected];
        }
    }
    
}

-(void)dealloc{
    
    //移除KVO观察
    [self.model removeObserver:self forKeyPath:KVO_KEY_IS_SELECTED];
    
}

-(void)setModel:(CSSelectableModel *)model{
    
    if(self.model != nil){
        [self.model removeObserver:self forKeyPath:KVO_KEY_IS_SELECTED];
    }
    
    _model = model;
    
    //设置按钮选中状态
    [self changeSelectImage:_model.isSelected];
    
    //KVO观察
    [self.model addObserver:self forKeyPath:KVO_KEY_IS_SELECTED options:NSKeyValueObservingOptionNew context:nil];
    
    //设置类型名称
    self.typeNameLabel.text = model.name == nil ? model.content : model.name;
}

-(void)changeSelectImage:(Boolean) isSelected{
    
    //设置按钮选中状态
    if (isSelected) {
        UIImage *image = GET_CSUIKIT_BUNDLE_IMAGE(@"checkSelected");
        [self.checkImageView setImage:GET_CSUIKIT_BUNDLE_IMAGE(@"after02")];
        
        if(self.selectedColor != nil){
            self.backgroundColor = self.selectedColor;
        }else{
            self.backgroundColor = COLOR_CONTROLER_SELECTED_MAIN;
        }
    }else{
        [self.checkImageView setImage:[UIImage imageNamed:@""]];
        self.backgroundColor = COLOR_CONTROLER_UNSELECTED_MAIN;
    }
    
}

-(UILabel *)typeNameLabel{
    if (_typeNameLabel == nil) {
        _typeNameLabel = [[UILabel alloc]init];
        _typeNameLabel.font = [UIFont systemFontOfSize:FONT_SIZE_REM];
        _typeNameLabel.textColor = COLOR_TEXT_2;
        _typeNameLabel.numberOfLines = 0;
    }
    return _typeNameLabel;
}

-(UIImageView *)checkImageView{
    if (_checkImageView == nil) {
        _checkImageView = [[UIImageView alloc]init];
    }
    return _checkImageView;
}

@end


@implementation SubSelectCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self layoutView];
    }
    return self;
}

-(void)layoutView{
    
    CGFloat imageHeight = 13.0;
    CGFloat imageWidth = imageHeight / 9.0 * 13.0;
    CGFloat labelWidth = kWindowW - 40.0 - imageWidth - 20.0;
    CGFloat labelHeight = SELECT_CELL_HEIGHT - 20.0;
    self.typeNameLabel.frame = CGRectMake(40, 10, labelWidth, labelHeight);
    [self addSubview:self.typeNameLabel];
    
    self.checkImageView.frame = CGRectMake(kWindowW - 10 - imageWidth, (SELECT_CELL_HEIGHT - imageHeight)/2.0, imageWidth, imageHeight);
    [self addSubview:self.checkImageView];
    
}

-(UILabel *)typeNameLabel{
    if (_typeNameLabel == nil) {
        _typeNameLabel = [[UILabel alloc]init];
        _typeNameLabel.font = [UIFont systemFontOfSize:FONT_SIZE_REM];
        _typeNameLabel.textColor = COLOR_TEXT_2;
        _typeNameLabel.numberOfLines = 0;
    }
    return _typeNameLabel;
}

-(UIImageView *)checkImageView{
    if (_checkImageView == nil) {
        _checkImageView = [[UIImageView alloc]init];
    }
    return _checkImageView;
}

#define KVO_KEY_IS_SELECTED @"isSelected"

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:KVO_KEY_IS_SELECTED]) {//安装功能项修改
        {
            [self changeSelectImage:self.model.isSelected];
        }
    }
}

-(void)dealloc{
    //移除KVO观察
    [self.model removeObserver:self forKeyPath:KVO_KEY_IS_SELECTED];
}

-(void)setModel:(CSSelectableModel *)model{
    
    if(self.model != nil){
        [self.model removeObserver:self forKeyPath:KVO_KEY_IS_SELECTED];
    }
    
    _model = model;
    
    //设置按钮选中状态
    [self changeSelectImage:_model.isSelected];
    
    //KVO观察
    [self.model addObserver:self forKeyPath:KVO_KEY_IS_SELECTED options:NSKeyValueObservingOptionNew context:nil];
    
    //设置类型名称
    self.typeNameLabel.text = model.name == nil ? model.content : model.name;
}

-(void)changeSelectImage:(Boolean) isSelected{
    //设置按钮选中状态
    if (isSelected) {
        [self.checkImageView setImage:GET_CSUIKIT_BUNDLE_IMAGE(@"after02")];
        self.backgroundColor = COLOR_CONTROLER_SELECTED_SUB;
    }else{
        [self.checkImageView setImage:[UIImage imageNamed:@""]];
        self.backgroundColor = COLOR_CONTROLER_UNSELECTED_SUB;
    }
}

@end




@interface CS_Pop_MultitpleSelectView()<UITableViewDelegate, UITableViewDataSource>

/**
 *  点击确定后的回调方法
 */
@property (nonatomic, copy) SelectedCompletedBlock completeHandler;

/**
 * 可选择的模型对象
 */
@property (nonatomic, strong) NSArray *selectableModels;

/**
 * 最终显示在列表上的模型对象
 */
@property (nonatomic, strong) NSMutableArray *finalDisplayModels;

/**
 * 选择列表
 */
@property (strong, nonatomic) UITableView *selectTableView;

/**
 * 保存按钮
 */
@property (strong, nonatomic) UIButton *saveButton;

@property (nonatomic, strong) NSString *title;

@end

@implementation CS_Pop_MultitpleSelectView

/**
 * 夺取多选框视图框
 * @param selectModels 选择项集合 要求类型为（SelectModle）
 * @param titleName 标题名称
 * @param selectCompletedHandler 选择完成回调处理
 */
+(instancetype)pop_multitpleSelectView:(NSArray *)selectableModels
                         titleName:(NSString *)titleName
            selectCompletedHandler:(SelectedCompletedBlock)selectCompletedHandler{
    CS_Pop_MultitpleSelectView *multitpleSelectView = [CS_Pop_MultitpleSelectView new];
    multitpleSelectView.selectableModels = selectableModels;
    multitpleSelectView.completeHandler = selectCompletedHandler;
    multitpleSelectView.title = titleName;
    [multitpleSelectView initVariable];
    
    return multitpleSelectView;
}

/**
 * 点击保存
 */
- (void)saveClick {
    
    NSMutableString *selectedNames = [NSMutableString new];
    NSMutableString *selectedCodes = [NSMutableString new];
    NSString *resultSelectedNames = @"";
    NSString *resultSelectedCodes = @"";
    
    if (self.selectableModels != nil) {//如果有可选项
        //拼装选中的类型
        for (CSSelectableModel *selectableModel in self.finalDisplayModels) {
            if (selectableModel.isSelected) {
                [selectedNames appendString:[NSString stringWithFormat:@"%@,", selectableModel.name]];
                [selectedCodes appendString:[NSString stringWithFormat:@"%@,", selectableModel.code]];
            }
        }
        
        //去掉最后一位逗号
        if ((selectedCodes != nil && ![selectedCodes isEqualToString:@""])) {
            
            NSRange rangeCode;
            rangeCode.location = 0;
            rangeCode.length = selectedCodes.length - 1;
            NSRange rangeNames;
            rangeNames.location = 0;
            rangeNames.length = selectedNames.length - 1;
            
            resultSelectedNames = [selectedNames substringWithRange:rangeNames];
            resultSelectedCodes = [selectedCodes substringWithRange:rangeCode];
        }
    }
    
    //回调处理
    if(self.completeHandler != nil){
        self.completeHandler(resultSelectedNames, resultSelectedCodes);
    }
    
    //关闭当前视图
    [self.superKLCPopup dismiss:YES];
    
}

/**
 *  初始化变量
 */
-(void)initVariable{
    
    CGFloat cellHeight = SELECT_CELL_HEIGHT;
    CGFloat viewWidth = SELECT_VIEW_WIDTH;
    int rowCount = 8;
    
    CGFloat viewHeight = SELECT_CELL_HEIGHT * rowCount;
    self.frame = CGRectMake(0, 0, viewWidth, viewHeight);
    self.backgroundColor = COLOR_THEME;
    
    self.titleLabel = [UILabel new];
    self.titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE_REM + 2.0];
    self.titleLabel.textColor = COLOR_WHITE;
    self.titleLabel.frame = CGRectMake(0, 0, SELECT_VIEW_WIDTH, SELECT_CELL_HEIGHT);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = self.title;
    self.titleLabel.layer.cornerRadius = 5;
    self.titleLabel.layer.masksToBounds = YES;
    [self addSubview:self.titleLabel];
    
    
    UIView *bottomView = [[UIView alloc]init];
    bottomView.frame = CGRectMake(0, SELECT_CELL_HEIGHT * (rowCount - 1) - 5, SELECT_VIEW_WIDTH, SELECT_CELL_HEIGHT + 5);
    bottomView.layer.cornerRadius = 5;
    bottomView.layer.masksToBounds = YES;
    bottomView.backgroundColor = COLOR_WHITE;
    [self addSubview:bottomView];
    
    self.selectTableView.delegate = self;
    self.selectTableView.dataSource = self;
    [self.selectTableView registerClass:[MainSelectCell class] forCellReuseIdentifier:CELL_STYLE_MAIN_SELECTABLE_CELL];
    [self.selectTableView registerClass:[SubSelectCell class] forCellReuseIdentifier:CELL_STYLE_SUB_SELECTALBE_CELL];
    self.selectTableView.tableFooterView=[[UIView alloc]init];//关键语句
    self.selectTableView.backgroundColor = [UIColor whiteColor];
    self.selectTableView.bounces = NO;
    self.selectTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.selectTableView.frame = CGRectMake(0, SELECT_CELL_HEIGHT, SELECT_VIEW_WIDTH, (rowCount - 2) * SELECT_CELL_HEIGHT);
    [self addSubview:self.selectTableView];
    
    self.saveButton.frame = CGRectMake((SELECT_VIEW_WIDTH - BUTOTN_WIDTH)/2.0, (rowCount - 1) * SELECT_CELL_HEIGHT + (SELECT_CELL_HEIGHT - BUTTON_HEIGHT)/2.0, BUTOTN_WIDTH, BUTTON_HEIGHT);
    STYLE_SAVE_BUTTON(self.saveButton);
    [self addSubview:self.saveButton];
    
    [self initFinalDisplayModels];
}

/**
 * 判断是否为第一层选择项
 */
-(BOOL)isParentModel:(CSSelectableModel *)selectableModel{
    
    for (CSSelectableModel *model in self.selectableModels) {
        if (selectableModel == model) {
            return YES;
        }
    }
    
    return NO;
}

/**
 * 初始化最终要显示在视图列表上的视图模型
 */
-(void)initFinalDisplayModels{
    
    for (CSSelectableModel *selectableModel in self.selectableModels) {
        [self.finalDisplayModels addObject:selectableModel];
        for (CSSelectableModel *model in selectableModel.subItems) {
            [self.finalDisplayModels addObject:model];
        }
    }
}


#pragma mark --- UITableViewDelegate/UITableViewDataSource

//移除分割线
//kRemoveCellSeparator
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.finalDisplayModels.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CSSelectableModel *model = [self.finalDisplayModels objectAtIndex:indexPath.row];
    
    if (![self isParentModel:model]) {
        SubSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_STYLE_SUB_SELECTALBE_CELL];
        if (cell==nil) {
            cell = [[SubSelectCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_STYLE_SUB_SELECTALBE_CELL];
        }
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else{
        MainSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_STYLE_MAIN_SELECTABLE_CELL];
        if (cell==nil) {
            cell = [[MainSelectCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_STYLE_MAIN_SELECTABLE_CELL];
        }
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //改变选中状态
    CSSelectableModel *model = (CSSelectableModel *)[self.finalDisplayModels objectAtIndex:indexPath.row];
    
    model.isSelected = ! model.isSelected;
    
    //子项同时改变选中状态
    if (model.subItems!=nil) {
        for (CSSelectableModel *subModel in model.subItems) {
            subModel.isSelected = model.isSelected;
        }
    }
}

-(NSMutableArray *)finalDisplayModels{
    if (_finalDisplayModels == nil) {
        _finalDisplayModels = [NSMutableArray new];
    }
    return _finalDisplayModels;
}

-(UITableView *)selectTableView{
    if (_selectTableView == nil) {
        _selectTableView = [[UITableView alloc]init];
    }
    return _selectTableView;
}

-(UIButton *)saveButton{
    if (_saveButton == nil) {
        _saveButton = [[UIButton alloc]init];
        [_saveButton addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
        [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
    }
    return _saveButton;
}

@end
